package com.example.springsecuritydemo.configuration;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;

/**
 * 核心类
 *  AuthenticationManager 认证管理类
 *  AuthenticationProvider 提供认证逻辑
 *  UserDetailsService 加载用户信息
 *  UserDetails
 *  AbstractAuthenticationProcessingFilter
 *  流程：
 *  生成未认证的AuthenticationToken
 *        ↑（获取信息）           （根据AuthenticationToken分配provider）
 *  AuthenticationFilter   ->     AuthenticationManager    ->    AuthenticationProvider
 * 		                                                              ↓（认证）
 * 		                                                      UserDetails（一般查询数据库获取）
 * 	                                                        	      ↓（通过）
 * 	                                                         生成认证成功的AuthenticationToken
 * 	                                                                      ↓（存放）
 * 	                                                              SecurityContextHolder
 *
 * 	自定义登录认证demo：https://juejin.im/post/5a3b7f5c6fb9a0452936ee2a
 *
 */
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    public UserDetailsService userDetailsService() {
        InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
        manager.createUser(User.withDefaultPasswordEncoder().username("user").password("password").roles("USER").build());
        return manager;
    }

    @Override
    public void configure(WebSecurity web) throws Exception {

    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .and()
                .httpBasic();
    }
}
